<template>
  <div class="user-management">
    <div class="page-header">
      <h1>用户管理</h1>
      <div class="header-actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索用户名/邮箱/手机号"
          class="search-input"
          clearable
          @clear="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="statusFilter" placeholder="状态筛选" clearable @change="handleSearch">
          <el-option label="正常" :value="1" />
          <el-option label="禁用" :value="2" />
          <el-option label="未激活" :value="0" />
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </div>
    </div>
    
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="users"
        style="width: 100%"
        border
      >
        <el-table-column type="index" width="50" />
        
        <el-table-column prop="username" label="用户名" min-width="100" />
        
        <el-table-column prop="nickname" label="昵称" min-width="100">
          <template #default="scope">
            {{ scope.row.nickname || '未设置' }}
          </template>
        </el-table-column>
        
        <el-table-column label="头像" width="80" align="center">
          <template #default="scope">
            <el-avatar 
              :size="40" 
              :src="scope.row.avatar" 
              :icon="UserFilled"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="email" label="邮箱" min-width="150" show-overflow-tooltip />
        
        <el-table-column prop="phone" label="手机号" min-width="120" show-overflow-tooltip />
        
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="scope">
            {{ scope.row.gender === 1 ? '男' : scope.row.gender === 2 ? '女' : '未设置' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="role" label="角色" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.role === 'admin' ? 'danger' : 'success'">
              {{ scope.row.role === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createdAt" label="注册时间" min-width="180" show-overflow-tooltip />
        
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              :type="scope.row.status === 1 ? 'danger' : 'success'"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 用户编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="编辑用户"
      width="600px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" disabled />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" />
        </el-form-item>
        
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="userForm.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">禁用</el-radio>
            <el-radio :label="0">未激活</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="userForm.birthday"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="所在地" prop="location">
          <el-input v-model="userForm.location" />
        </el-form-item>
        
        <el-form-item label="个人简介" prop="bio">
          <el-input
            v-model="userForm.bio"
            type="textarea"
            :rows="3"
            placeholder="请输入个人简介"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUserForm" :loading="submitting">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, UserFilled } from '@element-plus/icons-vue';
import { getUserList, updateUser } from '@/api/user';

// 状态变量
const loading = ref(false);
const users = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const searchQuery = ref('');
const statusFilter = ref('');
const dialogVisible = ref(false);
const submitting = ref(false);

// 用户表单
const userFormRef = ref(null);
const userForm = reactive({
  userId: '',
  username: '',
  email: '',
  phone: '',
  nickname: '',
  gender: 1,
  role: '',
  status: 1,
  birthday: '',
  location: '',
  bio: ''
});

// 表单验证规则
const userRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  nickname: [
    { required: false, message: '请输入昵称', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '未激活';
    case 1: return '正常';
    case 2: return '禁用';
    default: return '未知';
  }
};

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 0: return 'info';
    case 1: return 'success';
    case 2: return 'danger';
    default: return 'info';
  }
};

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    };
    
    // 添加搜索条件
    if (searchQuery.value) {
      // 根据输入内容判断是用户名、邮箱还是手机号
      if (searchQuery.value.includes('@')) {
        params.email = searchQuery.value;
      } else if (/^\d+$/.test(searchQuery.value)) {
        params.phone = searchQuery.value;
      } else {
        params.username = searchQuery.value;
      }
    }
    
    // 添加状态筛选
    if (statusFilter.value !== '') {
      params.status = statusFilter.value;
    }
    
    const response = await getUserList(params);
    
    if (response.code === 200 && response.data) {
      users.value = response.data.list;
      total.value = response.data.total;
    } else {
      ElMessage.error(response.message || '获取用户列表失败');
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取用户列表失败，请稍后再试');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchUsers();
};

// 编辑用户
const handleEdit = (row) => {
  // 复制用户数据到表单
  Object.keys(userForm).forEach(key => {
    if (key in row) {
      userForm[key] = row[key];
    }
  });
  
  // 确保userId字段正确设置
  userForm.userId = row.userId;
  
  dialogVisible.value = true;
};

// 提交用户表单
const submitUserForm = () => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        // 调用API更新用户信息
        const response = await updateUser(userForm.userId, {
          username: userForm.username,
          email: userForm.email,
          phone: userForm.phone,
          nickname: userForm.nickname,
          gender: userForm.gender,
          role: userForm.role,
          status: userForm.status,
          birthday: userForm.birthday,
          location: userForm.location,
          bio: userForm.bio
        });
        
        if (response.code === 200) {
          ElMessage.success('更新用户成功');
          dialogVisible.value = false;
          fetchUsers();
        } else {
          ElMessage.error(response.message || '更新用户失败');
        }
      } catch (error) {
        console.error('更新用户失败:', error);
        ElMessage.error(error.message || '更新用户失败');
      } finally {
        submitting.value = false;
      }
    }
  });
};

// 切换用户状态
const handleToggleStatus = (row) => {
  const newStatus = row.status === 1 ? 2 : 1;
  const statusText = newStatus === 1 ? '启用' : '禁用';
  
  ElMessageBox.confirm(
    `确定要${statusText}用户 "${row.username}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        // 使用updateUser函数更新用户状态
        const response = await updateUser(row.userId, {
          username: row.username,
          status: newStatus
        });
        
        if (response.code === 200) {
          ElMessage.success(`${statusText}用户成功`);
          fetchUsers();
        } else {
          ElMessage.error(response.message || `${statusText}用户失败`);
        }
      } catch (error) {
        console.error(`${statusText}用户失败:`, error);
        ElMessage.error(`${statusText}用户失败`);
      }
    })
    .catch(() => {
      // 用户取消操作
    });
};

// 分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchUsers();
};

// 页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchUsers();
};

onMounted(() => {
  fetchUsers();
});
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 500px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .header-actions {
    width: 100%;
    flex-wrap: wrap;
  }
  
  .search-input {
    flex: 1;
  }
}
</style>